﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Newtonsoft.Json.Linq;
using Art_Gallery;
using System.Diagnostics;

namespace CMCCMicroBlog
{
    public partial class LoginPivotPage : PhoneApplicationPage
    {
        public LoginPivotPage()
        {
            InitializeComponent();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            string mobile = AppSettingHelper.GetValueOrDefault<string>(App.LOGIN_MOBILE, "");
            string passwd = AppSettingHelper.GetValueOrDefault<string>(App.LOGIN_PASSWD,"");
            bool isAutoLogin = AppSettingHelper.GetValueOrDefault<bool>(App.LOGIN_AUTO,false);

            if (!mobile.Equals(""))
            {
                mobileTextBox.Text = mobile;
            }
            
            if(!passwd.Equals(""))
            {
                passwdTextBox.Password = passwd;
            }

            if (!mobile.Equals("") && !passwd.Equals("")&&isAutoLogin)
            {
                doLogin(mobile, passwd);
            }
        }

        public void doLogin(string mobile,string passwd)
        {
            //检查网络连接,如果不可用,则返回,取消登陆
            if (!LoginPivotPage.IsNetWorkAvailable())
            {
                return;
            }

            ApplicationBar.IsVisible = false;
            loginProgressBar.Visibility = Visibility.Visible;

            try
            {
                WebClient wc = new WebClient();
                string url = string.Format(App.API_URL + "op=Login.login&mobile={0}&pwd={1}&version=2", mobile, passwd);
                wc.DownloadStringAsync(new Uri(url, UriKind.Absolute));
                wc.DownloadStringCompleted += (s, e) =>
                {
                    JObject jo = JObject.Parse(e.Result);

                    if (jo["error_code"].ToString() == "0")
                    {
                        App.userSessionId = jo["data"]["sid"].ToString();
                        NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                        SaveLoginInfo(jo);
                        return;
                    }
                    else
                    {
                        MessageBox.Show("用户名或密码错误！", "抱歉", MessageBoxButton.OK);
                        loginProgressBar.Visibility = Visibility.Collapsed;
                        ApplicationBar.IsVisible = true;
                    }
                };
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                Debug.WriteLine(e.StackTrace);
                MessageBox.Show("您当前的网络连接状态不好，请稍候再试！", "抱歉", MessageBoxButton.OK);
                loginProgressBar.Visibility = Visibility.Collapsed;
                ApplicationBar.IsVisible = true;
            }
        }

        private void SaveLoginInfo(JObject jo)
        {

            //记录手机号，密码，是否自动登陆等信息
            AppSettingHelper.AddOrUpdateValue(App.LOGIN_MOBILE, mobileTextBox.Text);
            AppSettingHelper.AddOrUpdateValue(App.LOGIN_AUTO, autoLoginCheckBox.IsChecked);

            AppSettingHelper.AddOrUpdateValue(App.SCREENNAME, jo["data"]["profile"]["screenname"].ToString());

            if (autoLoginCheckBox.IsChecked!=false)
            {
                AppSettingHelper.AddOrUpdateValue(App.LOGIN_PASSWD, passwdTextBox.Password);

                AppSettingHelper.AddOrUpdateValue(App.SID, jo["data"]["sid"].ToString());
                AppSettingHelper.AddOrUpdateValue(App.UID, jo["data"]["profile"]["user_id"].ToString());
                
            }
        }

        //登陆
        private void loginIconButton_Click(object sender, EventArgs e)
        {
            string mobile = mobileTextBox.Text;
            string passwd = passwdTextBox.Password;
            doLogin(mobile,passwd);
        }

        private void accountTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            TextBox tb = (TextBox)sender;
            tb.SelectAll();
        }

        public static bool IsNetWorkAvailable(){
            bool isAvailable= Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsNetworkAvailable;
            if (!isAvailable)
            {
                MessageBox.Show("您没有可用的网络连接，请检查手机设置！", "抱歉", MessageBoxButton.OK);
            }
            return isAvailable;
        }
    }
}